<template>
  <div class="common-layout">
    <el-container style="height: 100vh;">
      <!--头部-->
      <el-header
          style="position: sticky; top: 0; z-index: 1000; background: #fff; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
        <div class="header-content">
          <h1 class="system-title">记账分析系统</h1>
          <div class="header-actions">
            <el-dropdown @command="handleUserCommand">
              <el-avatar class="header_user">{{ userStore.userInfo?.nickname || '云君' }}</el-avatar>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="teamManagement">团队维护</el-dropdown-item>
                  <el-dropdown-item command="switchAccount">切换账户</el-dropdown-item>
                  <el-dropdown-item command="changeAccount">修改账户</el-dropdown-item>
                  <el-dropdown-item command="cancelAccount">注销账户</el-dropdown-item>
                  <el-dropdown-item command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>

      <el-container>
        <!--侧边栏-->
        <el-aside width="240px"
                  style="position: sticky; top: 60px; height: calc(100vh - 60px); overflow-y: auto; background: #fff; border-right: 1px solid #e6e6e6;">
          <el-scrollbar>
            <el-menu :default-openeds="['1', '3']" :default-active="activeMenu" class="custom-menu">
              <el-sub-menu index="1">
                <template #title>
                  <el-icon>
                    <HomeFilled/>
                  </el-icon>
                  我的记账信息
                </template>
                <el-menu-item-group>
                  <!--消费类型:动态渲染消费类型列表--->
                  <template v-if="loading">
                    <el-menu-item index="loading">
                      <el-icon>
                        <Loading/>
                      </el-icon>
                      <span>加载中...</span>
                    </el-menu-item>
                  </template>
                  <template v-else>
                    <el-menu-item
                        v-for="category in displayCategories"
                        :key="'1-' + category.id"
                        :index="'1-' + category.id"
                        @click="handleCategoryClick(category)"
                        class="menu-item-hover">
                      <el-icon>
                        <component :is="category.icon || 'Coin'"/>
                      </el-icon>
                      {{ category.name }}
                    </el-menu-item>
                  </template>
                </el-menu-item-group>
              </el-sub-menu>
              <el-sub-menu index="2">
                <template #title>
                  <el-icon>
                    <TrendCharts/>
                  </el-icon>
                  记账信息统计
                </template>
                <el-menu-item-group>
                  <el-menu-item index="2-1" @click="handleMenuClick('statistics', 'currentMonth')"
                                class="menu-item-hover">
                    <el-icon>
                      <PieChart/>
                    </el-icon>
                    本月消费
                  </el-menu-item>
                  <el-menu-item index="2-2" @click="handleMenuClick('statistics', 'compareWithLastMonth')"
                                class="menu-item-hover">
                    <el-icon>
                      <PieChart/>
                    </el-icon>
                    与上月相比
                  </el-menu-item>
                  <el-menu-item index="2-3" @click="handleMenuClick('statistics', 'trend')" class="menu-item-hover">
                    <el-icon>
                      <PieChart/>
                    </el-icon>
                    总体的消费趋势
                  </el-menu-item>
                </el-menu-item-group>
              </el-sub-menu>
              <el-sub-menu index="3">
                <template #title>
                  <el-icon>
                    <List/>
                  </el-icon>
                  AI 智能服务
                </template>
                <el-menu-item-group>
                  <el-menu-item
                      v-for="(service, index) in aiServices"
                      :key="'3-' + (index+1)"
                      :index="'3-' + (index+1)"
                      @click="handleMenuClick('ai', service)"
                      class="menu-item-hover">
                    <el-icon>
                      <component :is="service.icon"/>
                    </el-icon>
                    {{ service.name }}
                  </el-menu-item>
                </el-menu-item-group>
              </el-sub-menu>
            </el-menu>
          </el-scrollbar>
        </el-aside>
        <!--主要部分-->
        <el-main style="overflow-y: auto; height: calc(100vh - 60px); background: #f5f7fa; padding: 24px;">
          <!-- 加载状态 -->
          <div v-if="loading">
            <div class="loading-container">
              <el-empty description="加载数据中..." :image-size="100"/>
            </div>
          </div>

          <!-- 分类详情视图 -->
          <div v-else-if="currentView.type === 'category' && currentView.data?.id !== 0">
            <CategoryDetail
                :category="currentView.data"/>
          </div>

          <!-- 全部分类概览视图 -->
          <div v-else-if="currentView.type === 'category' && currentView.data?.id === 0">
            <div class="page-header">
              <el-icon size="24">
                <component :is="currentView.data?.icon || 'Coin'"/>
              </el-icon>
              <h2>全部消费记录</h2>
            </div>

            <el-row :gutter="20">
              <el-col v-for="category in categories.filter(c => c.id !== 0)" :key="category.id" :span="8"
                      style="margin-bottom: 20px;">
                <CategoryCard
                    :category="category"
                    :total-amount-last="getCategoryBlurData(category.id, 'lastMonth')"
                    :total-amount-current="getCategoryBlurData(category.id, 'currentMonth')"
                    :total-amount-history="getCategoryBlurData(category.id, 'history')"
                    @view-detail="handleCategoryClick"/>
              </el-col>
            </el-row>
          </div>

          <!-- 统计视图 -->
          <div v-else-if="currentView.type === 'statistics'">
            <StatisticsView :type="currentView.data"/>
          </div>

          <!-- AI服务视图 -->
          <div v-else-if="currentView.type === 'ai'">
            <div class="page-header">
              <h2>{{ currentView.data?.name }}</h2>
            </div>
            <el-card
                style="max-width: 800px; margin: 0 auto; height: 400px; display: flex; align-items: center; justify-content: center;">
              <el-empty description="功能开发中，敬请期待" :image-size="120"/>
            </el-card>
          </div>

          <!-- 空状态视图 -->
          <div v-else>
            <div class="empty-container">
              <el-empty description="请选择左侧菜单查看内容" :image-size="150"/>
            </div>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import {computed, nextTick, onMounted, reactive, ref} from 'vue'
import {useRouter} from 'vue-router'
import {useUserStore} from '@/stores/user'
import {HomeFilled, List, Loading, PieChart, TrendCharts} from '@element-plus/icons-vue'
import {consumptionTypeApi} from '@/api/consumptionType.js'
import {consumptionRecordPersonalApi} from '@/api/consumptionRecordPersonal.js'
import {ElMessage} from "element-plus";

// 导入组件
import CategoryCard from '@/components/common/CategoryCard.vue';
import CategoryDetail from '@/components/common/CategoryDetail.vue';
import StatisticsView from '@/components/common/StatisticsView.vue';

const router = useRouter()
const userStore = useUserStore()

// AI服务列表
const aiServices = ref([
  {name: '记账智能分析', icon: 'Loading'},
  {name: '性价比分析师', icon: 'ChatRound'},
  {name: 'AI 推荐', icon: 'Compass'}
])

// 当前激活的菜单
const activeMenu = ref('1-0')

// 加载状态
const loading = ref(true)
// 从数据库获取的分类数据
const categories = ref([])
// 分类数据计算
const blurData = ref([])

// 当前视图状态
const currentView = reactive({
  type: 'category',
  data: {id: 0, name: '全部', icon: 'View'}
})

// 显示的分类数据（包含全部选项）
const displayCategories = computed(() => {
  // 确保全部选项始终是第一个
  const allCategory = {id: 0, name: '全部', icon: 'View'}
  return [allCategory, ...categories.value]
})

// 从数据库获取分类数据
const getCategorys = async () => {
  try {
    loading.value = true
    const response = await consumptionTypeApi.queryAll()
    if (response.code === 200) {
      // 过滤掉可能包含的全部选项，确保由displayCategories统一处理
      categories.value = response.data.filter(cat => cat.id !== 0)
    } else {
      ElMessage.info(response.message ? response.message : '查询消费类型失败,请联系管理人员')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('获取分类数据失败，展示默认数据')
  } finally {
    loading.value = false
    // 确保当前视图数据与最新分类同步
    updateCurrentViewData()
  }
}

// 从数据库获取每一个分类数据模糊数据
const getAllCategoryData = async () => {
    loading.value = true
    const id = userStore.userInfo.id
    const response = await consumptionRecordPersonalApi.queryAllBlurData(id)
    if (response.code === 200) {
      blurData.value = response.data
    } else {
      ElMessage.info(response.message ? response.message : '查询消费类型失败,请联系管理人员')
    }
}

// 更新当前视图数据
const updateCurrentViewData = () => {
  if (currentView.type === 'category') {
    const currentId = currentView.data?.id || 0
    currentView.data = displayCategories.value.find(cat => cat.id === currentId) || displayCategories.value[0]
  }
}

// 处理分类菜单点击事件
const handleCategoryClick = (category) => {
  activeMenu.value = `1-${category.id}`
  currentView.type = 'category'
  currentView.data = category

  if (category.id === 0) {
    getCategorys()
    getAllCategoryData()
  }

  // 强制更新CategoryDetail组件
  nextTick(() => {
    // 触发CategoryDetail组件的数据刷新
  })

}
// 计算分类总支出
const getCategoryBlurData = (categoryId, type) => {
  const categoryData = blurData.value.find(item => item.typeId === categoryId);

  if (!categoryData) return '0.00';

  switch (type) {
    case 'lastMonth':
      return categoryData.totalAmountLast || '0.00';
    case 'currentMonth':
      return categoryData.totalAmountCurrent || '0.00';
    case 'history':
      return categoryData.totalAmountHistory || '0.00';
    default:
      return '0.00';
  }
}

// 处理菜单点击事件
const handleMenuClick = (type, data) => {
  currentView.type = type
  currentView.data = data
}

// 处理用户下拉菜单命令
const handleUserCommand = (command) => {
  switch (command) {
    case 'switchAccount':
      // 后续会实现切换账户逻辑
      console.log('切换账户')
      break
    case 'logout':
      logout()
      break
    case 'teamManagement':
      // 后续会实现跳转到团队维护页面
      console.log('团队维护')
      break
    case 'cancelAccount':
      // 跳转到注销账户界面
      break
    case 'changeAccount':
      // 跳转到修改账户信息界面
      break
    default:
      break
  }
}

// 退出登录
const logout = () => {
  userStore.logout()
  router.push('/login')
}

// 组件挂载时获取数据
onMounted(() => {
  // 查询所有的消费类型分类
  getCategorys()
  // 从数据库获取每一个分类数据模糊数据
  getAllCategoryData()

  if (currentView.data?.id === 0) {
    getAllCategoryData()
  }
})
</script>

<style scoped>
/* 移除重复的选择器 */
.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
  padding: 0 24px;
}

.system-title {
  font-size: 24px;
  font-weight: 600;
  color: #409eff;
  margin: 0;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header_user {
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: transform 0.2s;
  width: 32px;
  height: 32px;
}

.header_user:hover {
  transform: scale(1.05);
}

.page-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 24px;
  padding-bottom: 12px;
  border-bottom: 2px solid #409eff;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.custom-menu {
  border-right: none;
  padding: 16px 0;
}

/* 统一菜单项样式 */
.menu-item-hover {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border-radius: 6px;
  margin: 2px 8px;
}

.menu-item-hover:hover {
  background-color: #ecf5ff !important;
  color: #409eff !important;
  transform: translateX(4px);
}

.loading-container,
.empty-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 400px;
}

/* 卡片悬停增强效果 */
:deep(.el-card) {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
</style>

